package br.com.etecmatao.dao.impl;

import br.com.etecmatao.dao.GenericDAO;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {

    private final Class<T> persistentClass;

    @Override
    public Class<T> getEntityClass() {
        return persistentClass;
    }

    protected EntityManager getEntityManager() {
        return EntityManagerProvider.getEntityManager();
    }

    @SuppressWarnings("unchecked")
    public GenericDAOImpl() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public GenericDAOImpl(final Class<T> persistentClass) {
        super();
        this.persistentClass = persistentClass;
    }

    @Override
    public T findById(final ID id) {
        final T result = getEntityManager().find(persistentClass, id);
        return result;
    }

    @Override
    public void delete(T entity) {
        EntityTransaction trans = getEntityManager().getTransaction();
        trans.begin();
        getEntityManager().remove(entity);
        trans.commit();
    }

    @Override
    public T update(T entity){
        EntityTransaction trans = getEntityManager().getTransaction();
        trans.begin();
        getEntityManager().merge(entity);
        trans.commit();
        return entity;
    }

    @Override
    public T save(T entity) {
        EntityTransaction trans = getEntityManager().getTransaction();
        trans.begin();
        getEntityManager().persist(entity);
        trans.commit();
        return entity;
    }
}